﻿using DncLite.Domain.Commands.Student;
using DncLite.Domain.Core.Bus;
using DncLite.Domain.Interfaces;
using DncLite.Domain.Models;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DncLite.Domain.CommandHandlers
{
    public class StudentCommandHandler : CommandHandler,
        IRequestHandler<RegisterStudentCommand, Unit>
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IMediatorHandler _bus;
        private IMemoryCache _cache;
        public StudentCommandHandler(
            IStudentRepository studentRepository
            ,IUnitOfWork uow, IMediatorHandler bus, IMemoryCache cache) : base(uow, bus, cache)
        {
            _studentRepository = studentRepository;
            _bus = bus;
            _cache = cache;
        }

        public Task<Unit> Handle(RegisterStudentCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return Task.FromResult(new Unit());
            }
            var student = new Student(Guid.NewGuid(), request.Name, request.Email, request.Phone, request.BirthDate);
            if (_studentRepository.GetByEmail(student.Email) != null)
            {
                var errorInfo = new List<string> {"邮箱已经存在" };
                _cache.Set("ErrorData", errorInfo);
                return Task.FromResult(new Unit());
            }
            _studentRepository.Add(student);
            if (Commit())
            {

            }
            return Task.FromResult(new Unit());
        }
    }
}
